<template>
  <div class="budget-container">
    <div class="budget-header">
      <h1>我的记账</h1>
      <div class="actions">
        <el-button type="primary" :icon="Plus" @click="goCreate">新增记账</el-button>
      </div>
    </div>

    <div v-if="userBudgets.length === 0" class="empty-wrap">
      <el-empty description="暂无记账记录">
        <el-button type="primary" @click="goCreate">立即新增</el-button>
      </el-empty>
    </div>

    <div v-else class="budget-list">
      <el-row :gutter="16">
        <el-col v-for="b in userBudgets" :key="b.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="budget-card" shadow="hover">
            <div class="card-header">
              <div class="title" @click="goDetail(b.id)">{{ b.title }}</div>
              <el-tag type="info" v-if="planMap[b.travelPlanId]">{{ planMap[b.travelPlanId].title }}</el-tag>
            </div>

            <div class="amounts">
              <div class="amount-item">
                <div class="label">总预算</div>
                <div class="value">¥{{ b.amount }}</div>
              </div>
              <div class="amount-item">
                <div class="label">已使用</div>
                <div class="value used">¥{{ b.usedAmount }}</div>
              </div>
            </div>

            <el-progress :percentage="Math.min(100, Math.round((b.usedAmount / (b.amount || 1)) * 100))" />

            <div class="card-actions">
              <el-button size="small" @click="goDetail(b.id)">查看详情</el-button>
              <el-button size="small" type="primary" @click="openEditBudget(b)">编辑</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑预算弹框 -->
    <el-dialog v-model="editDialogVisible" title="编辑记账" width="520px">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="总预算" prop="amount">
          <el-input-number v-model="editForm.amount" :min="0" :step="100" controls-position="right" />
        </el-form-item>
        <el-form-item label="关联计划" prop="travelPlanId">
          <el-select v-model="editForm.travelPlanId" placeholder="选择关联的旅行计划">
            <el-option v-for="p in travelPlans" :key="p.id" :label="p.title" :value="p.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBudgetBasic">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { getBudgets, updateBudget } from '../../api/budget'
import { getTravelPlans } from '../../api/travelPlan'
import { ElMessage } from 'element-plus'
import { authUtils } from '../../utils/auth'

const router = useRouter()

// 从后端加载当前用户的预算列表
const userBudgets = ref([])
// 加载旅行计划用于编辑弹框的关联选择
const travelPlans = ref([])

// 旅行计划映射，便于显示标题
const planMap = computed(() => {
  const m = {}
  travelPlans.value.forEach(p => { m[p.id] = p })
  return m
})

// 跳转
const goCreate = () => {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }
  router.push('/budget/new')
}
const goDetail = (id) => router.push(`/budget/${id}`)

// 编辑弹框
const editDialogVisible = ref(false)
const editFormRef = ref()
const editingBudgetId = ref(null)
const editForm = reactive({ title: '', amount: 0, travelPlanId: null })
const editRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入总预算', trigger: 'blur' }],
  travelPlanId: [{ required: true, message: '请选择关联计划', trigger: 'change' }],
}

async function loadBudgets() {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const res = await getBudgets()
    userBudgets.value = res.data
  } catch (e) {
    console.error('加载预算失败:', e)
    userBudgets.value = []
  }
}

async function loadTravelPlans() {
  try {
    const currentUserId = authUtils.getCurrentUser()?.id
    const list = await getTravelPlans(currentUserId ? { userId: currentUserId } : {})
    travelPlans.value = list
  } catch (e) {
    console.error('加载旅行计划失败:', e)
    travelPlans.value = []
  }
}

function openEditBudget(b) {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }
  
  editingBudgetId.value = b.id
  editForm.title = b.title
  editForm.amount = b.amount
  editForm.travelPlanId = b.travelPlanId
  editDialogVisible.value = true
}

async function saveBudgetBasic() {
  if (!authUtils.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (!editFormRef.value || !editingBudgetId.value) return
  editFormRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = { title: editForm.title, amount: editForm.amount, travelPlanId: editForm.travelPlanId }
    try {
      await updateBudget(editingBudgetId.value, payload)
      editDialogVisible.value = false
      await loadBudgets()
    } catch (e) {
      console.error('更新预算失败:', e)
    }
  })
}

onMounted(() => {
  loadBudgets()
  loadTravelPlans()
})
</script>

<style scoped>
.budget-container {
  padding: 20px;
}

.budget-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.actions {
  display: flex;
  gap: 8px;
}

.empty-wrap {
  max-width: 600px;
  margin: 40px auto;
}

.budget-list {
  margin-top: 8px;
}

.budget-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.title {
  font-weight: 600;
  cursor: pointer;
}

.amounts {
  display: flex;
  gap: 24px;
  margin: 8px 0;
}

.amount-item .label {
  color: #909399;
  font-size: 12px;
}

.amount-item .value {
  font-size: 18px;
  font-weight: 600;
}

.amount-item .value.used {
  color: #F56C6C;
}

.categories {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  color: #606266;
  font-size: 13px;
}

.categories .sep {
  margin: 0 4px;
  color: #C0C4CC;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}
</style>